package com.wisdom.view;

import org.json.JSONException;
import org.json.JSONObject;

import com.hisun.phone.core.voice.Log4Util;
import org.sipdroid.sipua.R;
import com.wisdom.VoiceApplication;
import com.wisdom.tools.CCPConfig;
import com.wisdom.tools.HttpUtil;
import com.wisdom.voip.VoiceHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

//注册设置密码activity
public class SetPwdActivity extends Activity {

	final String basicUrl="http://www.1000call.com";
    final String accessTokenUrl=basicUrl+"/api/mobile/accesstoken";
	public static final int WHAT_INIT_ERROR = 0x201C;
    Button btn_register;
    EditText editPassword;
    EditText editCode;
    String phone;
    TextView text_title;
    private ProgressDialog mDialog;
    Boolean IsResetPwd=false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_setpwd);
		initResourceRefs();
		Bundle extras = getIntent().getExtras(); 
		phone = extras.getString("phone"); 
		IsResetPwd=extras.getBoolean("resetpwd");
		if(IsResetPwd){
			text_title.setText("重设密码");
			btn_register.setText("确认");
		}
	}
	void initResourceRefs(){
		
		editCode=(EditText)findViewById(R.id.editTextCode);
		btn_register=(Button)findViewById(R.id.btn_register);
		editPassword=(EditText)findViewById(R.id.editText_pwd);
		text_title=(TextView)findViewById(R.id.texttitle);
		
	}
	private Handler helperHandler=new Handler(){
		 @Override
		 public void handleMessage(Message msg){
			 if(mDialog!=null){
				 mDialog.dismiss();
			 }
			 try{
				 if(msg.what==VoiceHelper.WHAT_ON_CONNECT){
					 if(!VoiceApplication.getInstance().isConnect()){
						 startAction();
						 VoiceApplication.getInstance().setConnect(true);
					 }
				 }else if(msg.what==VoiceHelper.WHAT_ON_DISCONNECT){
					 // do nothing
				 }else if(msg.what==WHAT_INIT_ERROR){
					 if(!VoiceApplication.getInstance().isConnect()){
						 showInitErrDialog();
					 }
				 }else{
					 Log4Util.d(VoiceHelper.WISDOMCALL_TAG,"Sorry , can't handle a message " + msg.what);
				 }
			 }catch(Exception e){
				 
			 }
			 super.handleMessage(msg);
		 }
	};
	
	public void register(View view) throws JSONException{
		//获取用户信息
		btn_register.setEnabled(false);
		String code=editCode.getText().toString();
		String password=editPassword.getText().toString();
		JSONObject object=new JSONObject("{Phone:\""+phone+"\",Code=\""+code+"\",Password=\""+password+"\"}");
		JSONObject data=HttpUtil.post(accessTokenUrl, object);
		if(data==null){
			btn_register.setEnabled(true);
			return;
		}
		if(data.getBoolean("success")){
			String accessToken=data.getString("AccessToken");
			String subAccount=data.getString("subAccount");
			String subToken=data.getString("subToken");
			String voipAccount=data.getString("voipAccount");
			String voipPwd=data.getString("voipPwd");
			String userId=data.getString("userId");
			String srcPhone=data.getString("srcPhone");
			String Balance=data.getString("balance");
			
			CCPConfig.setConfigProperties("accesstoken", accessToken);
			CCPConfig.setConfigProperties("sub_account",subAccount);
			CCPConfig.setConfigProperties("sub_token", subToken);
			CCPConfig.setConfigProperties("voip_account", voipAccount);
			CCPConfig.setConfigProperties("voip_password", voipPwd);
			CCPConfig.setConfigProperties("user_id", userId);
			CCPConfig.setConfigProperties("src_phone", srcPhone);
			CCPConfig.setConfigProperties("balance", Balance);
			
			CCPConfig.initProperties(getApplicationContext());
			if(IsResetPwd){
				Toast.makeText(getApplicationContext(),"成功重新设置密码！",Toast.LENGTH_SHORT).show();
			}
			VoiceHelper voiceHelper=VoiceApplication.getInstance().getVoiceHelper();
			if(voiceHelper!=null&&voiceHelper.getDevice()!=null){
				startAction();
			}else{
			//点击注册的时候初始化，以后是登陆的时候也要初始化
			mDialog = new ProgressDialog(SetPwdActivity.this);
			mDialog.setMessage(getString(R.string.dialog_message_text));
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.show();
			new SDKInitAsyncTask().execute();
			}
		}else{
			btn_register.setEnabled(true);
			Toast.makeText(getApplicationContext(), "验证验证码失败："+data.getString("message"),Toast.LENGTH_SHORT).show();
		}
		
	}	
	void showInitErrDialog(){
		new AlertDialog.Builder(this).setTitle(R.string.str_dialog_init_error_title)
		.setMessage(R.string.str_dialog_init_error_message)
		.setPositiveButton(R.string.dialog_btn,null).create().show();
}

class SDKInitAsyncTask extends AsyncTask<Void, Void, Void>{

@Override
protected Void doInBackground(Void... params) {
	VoiceApplication va= VoiceApplication.getInstance();
	va.initVoiceHelper(helperHandler);
	return null;
}
@Override
protected void onPostExecute(Void result){
	super.onPostExecute(result);
	startAction();



}}
@Override
protected void onDestroy() {
	super.onDestroy();
	helperHandler = null;
}
private void startAction(){
	Intent intent=new Intent();
	//intent.setClass(MainActivity.this,DialActivity.class);
	intent.setClass(SetPwdActivity.this,HomeTabHostActivity.class);
	startActivity(intent);
	//this.finish();
}
}
